问题描述(难度简单-155)
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
- push(x) – Push element x onto stack.
- pop() – Removes the element on top of the stack.
- top() – Get the top element.
- getMin() – Retrieve the minimum element in the stack.
Example:
1 | MinStack minStack = new MinStack(); |
方法一:双数组实现
一个数组作为输入的数值栈(stackArray),另一个数组作为最小值栈(minArray)。minArray[i]表示前i个stackArray中的最小值。每次pop出栈的时候同时pop一下minArray。空间复杂度为O(N),时间复杂度O(N)。
1 | package P155; |
方法二:双数组实现(缩减空间)
在方法一的基础上,实际上minArray没有必要存储N个最小值。
1 | package P155; |